package cn.rui.service.exam;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.rui.common.ContentBean;
import cn.rui.common.ResponseBean;
import cn.rui.mapper.UserMapper;
import cn.rui.mapper.exam.*;
import cn.rui.pojo.User;
import cn.rui.pojo.exam.*;
import cn.rui.pojo.vo.PageVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * @author 徽州大都督
 * @date 2021/6/25
 */

@Service
@Transactional(rollbackFor = Exception.class)
public class PaperService {

    @Autowired
    private PaperMapper paperMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private ManualPaperQuestionMapper manualPaperQuestionMapper;
    @Autowired
    private RandomPaperQuestionMapper randomPaperQuestionMapper;
    @Autowired
    private UserAnswerMapper userAnswerMapper;

    public ResponseBean randomPaperFindPage(PageVo pageVo, HttpSession session) {
        QueryWrapper<Paper> wrapper = new QueryWrapper<> ();
        Page<Paper> page = new Page<> (pageVo.getCurrentPage (), pageVo.getPageSize ());

        if (StrUtil.isNotBlank (pageVo.getQueryContent ())) {
            wrapper.like ("paper_name", pageVo.getQueryContent ());
        }

        //查询随机卷
        //wrapper.eq ("paper_type", 1);

        wrapper.orderByDesc ("create_time");

        IPage<Paper> randomPaperIPage = paperMapper.selectPage (page, wrapper);

        PageVo pv = new PageVo ();

        pv.setTotal (randomPaperIPage.getTotal ());

        List<Paper> paperList = randomPaperIPage.getRecords ();

        for (Paper paper : paperList) {
            User user = userMapper.selectById (paper.getUserId ());
            paper.setUser (user);
        }

        pv.setData (paperList);

        return ResponseBean.success (ContentBean.QuerySuccess, pv);
    }

    public ResponseBean randomPaperAdd(Paper paper, HttpSession session) {

        //判断单选题数量
        if (paper.getRadioNum () != 0) {
            QueryWrapper<ExamQuestion> wrapper = new QueryWrapper<> ();
            wrapper.eq ("question_type", 1);
            List<ExamQuestion> examQuestions = questionMapper.selectList (wrapper);
            if (examQuestions == null || examQuestions.size () < paper.getRadioNum ()) {
                return ResponseBean.error ("单选题数量不足");
            }
        }

        //判断多选题数量
        if (paper.getMultiNum () != 0) {
            QueryWrapper<ExamQuestion> wrapper = new QueryWrapper<> ();
            wrapper.eq ("question_type", 2);
            List<ExamQuestion> examQuestions = questionMapper.selectList (wrapper);
            if (examQuestions == null || examQuestions.size () < paper.getMultiNum ()) {
                return ResponseBean.error ("多选题数量不足");
            }
        }

        //判断判断题数量
        if (paper.getJudgeNum () != 0) {
            QueryWrapper<ExamQuestion> wrapper = new QueryWrapper<> ();
            wrapper.eq ("question_type", 3);
            List<ExamQuestion> examQuestions = questionMapper.selectList (wrapper);
            if (examQuestions == null || examQuestions.size () < paper.getJudgeNum ()) {
                return ResponseBean.error ("判断题数量不足");
            }
        }

        //判断简答题数量
        if (paper.getShortAnswerNum () != 0) {
            QueryWrapper<ExamQuestion> wrapper = new QueryWrapper<> ();
            wrapper.eq ("question_type", 4);
            List<ExamQuestion> examQuestions = questionMapper.selectList (wrapper);
            if (examQuestions == null || examQuestions.size () < paper.getShortAnswerNum ()) {
                return ResponseBean.error ("简答题数量不足");
            }
        }

        Date startDate = DateUtil.parse (paper.getStartCheckStr ());
        paper.setStartCheck (startDate);
        //随机卷
        paper.setPaperType (1);
        Object username = session.getAttribute ("username");
        QueryWrapper<User> wrapper = new QueryWrapper<> ();
        wrapper.eq ("username", username.toString ());
        User user = userMapper.selectOne (wrapper);
        paper.setUserId (user.getId ());

        paperMapper.insert (paper);

        return ResponseBean.success (ContentBean.SavaSuccess);
    }

    public ResponseBean randomPaperUpdateStatus(Long id) {
        Paper paper = paperMapper.selectById (id);
        if (paper.getStatus ()) {
            paper.setStatus (false);
        } else {
            paper.setStatus (true);
        }

        paperMapper.updateById (paper);

        return ResponseBean.success (ContentBean.UpdateSuccess);
    }

    public ResponseBean manualAdd(Paper paper, List<Long> checkList, HttpSession session) {
        Date startDate = DateUtil.parse (paper.getStartCheckStr ());
        paper.setStartCheck (startDate);
        //随机卷
        paper.setPaperType (2);
        Object username = session.getAttribute ("username");
        QueryWrapper<User> wrapper = new QueryWrapper<> ();
        wrapper.eq ("username", username.toString ());
        User user = userMapper.selectOne (wrapper);
        paper.setUserId (user.getId ());

        paperMapper.insert (paper);

        for (Long questionId : checkList) {
            ManualPaperQuestion manualPaperQuestion = new ManualPaperQuestion ();
            manualPaperQuestion.setPaperId (paper.getId ());
            manualPaperQuestion.setQuestionId (questionId);
            manualPaperQuestionMapper.insert (manualPaperQuestion);
        }

        return ResponseBean.success (ContentBean.SavaSuccess);
    }

    public ResponseBean randomPaperListFindPage(PageVo pageVo, HttpSession session) {
        QueryWrapper<Paper> wrapper = new QueryWrapper<> ();
        Page<Paper> page = new Page<> (pageVo.getCurrentPage (), pageVo.getPageSize ());

        if (StrUtil.isNotBlank (pageVo.getQueryContent ())) {
            wrapper.like ("paper_name", pageVo.getQueryContent ());
        }


        wrapper.eq ("status", true);

        wrapper.orderByDesc ("create_time");

        IPage<Paper> randomPaperIPage = paperMapper.selectPage (page, wrapper);

        PageVo pv = new PageVo ();

        pv.setTotal (randomPaperIPage.getTotal ());

        List<Paper> paperList = randomPaperIPage.getRecords ();

        for (Paper paper : paperList) {
            User user = userMapper.selectById (paper.getUserId ());
            paper.setUser (user);
            List<Integer> testUserIds = userAnswerMapper.selectUserIdByPaperId (paper.getId ());
            paper.setTestUserIds (testUserIds);
        }

        pv.setData (paperList);

        return ResponseBean.success (ContentBean.QuerySuccess, pv);
    }

    public ResponseBean randomFindPaperById(Long paperId, HttpSession session) {

        Object username = session.getAttribute ("username");
        QueryWrapper<User> wrapper = new QueryWrapper<> ();
        wrapper.eq ("username", username.toString ());
        User user = userMapper.selectOne (wrapper);
        //修改
        Paper paper = paperMapper.selectById (paperId);
        //明天继续
        if (paper.getPaperType () == 1) {
            //随机
            QueryWrapper<RandomPaperQuestion> wrapper1 = new QueryWrapper<> ();
            wrapper1.eq ("paper_id", paperId);
            wrapper1.eq ("user_id", user.getId ());
            List<RandomPaperQuestion> randomPaperQuestions = randomPaperQuestionMapper.selectList (wrapper1);


            //已经生成过此随机卷
            if (CollUtil.isNotEmpty (randomPaperQuestions)) {
                Set<Long> questionIds = new HashSet<> ();
                for (RandomPaperQuestion randomPaperQuestion : randomPaperQuestions) {
                    questionIds.add (randomPaperQuestion.getQuestionId ());
                }

                QueryWrapper<ExamQuestion> wrapper2 = new QueryWrapper<> ();
                wrapper2.in ("id", questionIds);
                wrapper2.orderByAsc ("question_type");
                List<ExamQuestion> examQuestions = questionMapper.selectList (wrapper2);
                paper.setQuestions (examQuestions);

                return ResponseBean.success (ContentBean.QuerySuccess, paper);
            }

            //未生成随机卷
            List<Long> questionId = new ArrayList<> ();
            if (paper.getRadioNum () != 0) {
                List<Long> questionIds2 = questionMapper.selectIdsByQuestionType (1);
                List questionIds = RandomUtil.randomEleList (questionIds2, paper.getRadioNum ());
                questionId.addAll (questionIds);
            }
            if (paper.getMultiNum () != 0) {
                List<Long> questionIds2 = questionMapper.selectIdsByQuestionType (2);
                List questionIds = RandomUtil.randomEleList (questionIds2, paper.getMultiNum ());
                questionId.addAll (questionIds);
            }
            if (paper.getJudgeNum () != 0) {
                List<Long> questionIds2 = questionMapper.selectIdsByQuestionType (3);
                List questionIds = RandomUtil.randomEleList (questionIds2, paper.getJudgeNum ());
                questionId.addAll (questionIds);
            }
            if (paper.getShortAnswerNum () != 0) {
                List<Long> questionIds2 = questionMapper.selectIdsByQuestionType (4);
                List questionIds = RandomUtil.randomEleList (questionIds2, paper.getShortAnswerNum ());
                questionId.addAll (questionIds);
            }

            //添加随机试题
            for (Long questionId2 : questionId) {
                RandomPaperQuestion randomPaperQuestion = new RandomPaperQuestion ();
                randomPaperQuestion.setPaperId (paperId);
                randomPaperQuestion.setQuestionId (questionId2);
                randomPaperQuestion.setUserId (user.getId ());
                randomPaperQuestionMapper.insert (randomPaperQuestion);
            }

            QueryWrapper<ExamQuestion> wrapper2 = new QueryWrapper<> ();
            wrapper2.in ("id", questionId);
            wrapper2.orderByAsc ("question_type");
            List<ExamQuestion> examQuestions = questionMapper.selectList (wrapper2);
            paper.setQuestions (examQuestions);
            return ResponseBean.success (ContentBean.QuerySuccess, paper);
        } else {
            //手动
            List<Long> longs = manualPaperQuestionMapper.queryQuestionIdByPaperId (paperId);
            QueryWrapper<ExamQuestion> wrapper1 = new QueryWrapper<> ();
            wrapper1.in ("id", longs);
            List<ExamQuestion> examQuestions = questionMapper.selectList (wrapper1);
            paper.setQuestions (examQuestions);
            return ResponseBean.success (ContentBean.QuerySuccess, paper);
        }
    }

    public ResponseBean userTestList(PageVo pageVo, HttpSession session) {
        Object username = session.getAttribute ("username");

        QueryWrapper<User> userQueryWrapper =  Wrappers.query ();
        userQueryWrapper.eq ("username",username.toString ());
        User user = userMapper.selectOne (userQueryWrapper);

        QueryWrapper<UserAnswer> userAnswerQueryWrapper = Wrappers.query ();
        userAnswerQueryWrapper.eq ("user_id",user.getId ());
        userAnswerQueryWrapper.select ("paper_id");
        List<Object> objects = userAnswerMapper.selectObjs (userAnswerQueryWrapper);

        List<Long> paperIds = new ArrayList<> ();

        if (CollUtil.isNotEmpty (objects)){
            List<Long> paperId = Convert.toList (Long.class, objects);
            paperIds.addAll (paperId);
        }

        QueryWrapper<Paper> paperQueryWrapper = Wrappers.query ();
        if (CollUtil.isNotEmpty (paperIds)){
            paperQueryWrapper.in ("id",paperIds);
        } else {
            paperQueryWrapper.eq ("id",0);
        }

        paperQueryWrapper.eq ("status", true);

        paperQueryWrapper.orderByDesc ("create_time");

        if (StrUtil.isNotBlank (pageVo.getQueryContent ())){
            paperQueryWrapper.like ("paper_name",pageVo.getQueryContent ());
        }

        Page<Paper> paperPage = new Page<> (pageVo.getCurrentPage (),pageVo.getPageSize ());

        IPage<Paper> userAnswerIPage = paperMapper.selectPage (paperPage, paperQueryWrapper);

        PageVo pv = new PageVo ();

        pv.setTotal (userAnswerIPage.getTotal ());

        List<Paper> paperList = userAnswerIPage.getRecords ();

        for (Paper paper : paperList) {
            paper.setUser (user);
            QueryWrapper<UserAnswer> userAnswerQueryWrapper2 = Wrappers.query ();
            userAnswerQueryWrapper2.eq ("user_id",user.getId ()).eq ("paper_id",paper.getId ());
            UserAnswer userAnswer = userAnswerMapper.selectOne (userAnswerQueryWrapper2);
            paper.setUserAnswer (userAnswer);
        }

        pv.setData (paperList);

        return ResponseBean.success (ContentBean.QuerySuccess, pv);
    }
}
